package ;

import flash.display.Bitmap;
import flash.display.DisplayObjectContainer;
import flash.geom.Point;
import flash.text.TextField;
import flash.text.TextFormat;

import Observer;

/**
 * ...
 * @author 
 */

class CounterView extends TextField, implements Observer
{
	private var mIcon: Bitmap;
	private var mFormat: TextFormat;
	private var mStringFormat: String;
	

	public function new(container: DisplayObjectContainer, ?x: Float, ?y: Float, ?counter: Counter) 
	{
		super();
		
		if (container != null) {
			container.addChild(this);
		}
		
		selectable = false;	
		multiline = false;
		wordWrap = false;
		maxChars = 0;
		mStringFormat = new String("");

		if (counter != null) {
			SetValue(counter.Get());
		}
		
		if (x != null) {
			this.x = x;
		}

		if (y != null) {
			this.y = y;
		}
		
		if (counter != null) {
			counter.Attach(this);
		}
	}
	
	
	public function Update(value: Int): Void
	{
		SetValue(value);
	}
	
	
	public function SetMaxChars(chars: Int)
	{
		maxChars = chars;
		
		SetValue(Std.parseInt(text));
	}
	
	
	public function SetValue(value: Int)
	{
		var str = IntToStr(value, maxChars);
		
		text = str;		
		
		if (mStringFormat.length > 0) {
			text = StringTools.replace(mStringFormat, "%%", str);
		}
				
		Decorate();		
	}
	
	
	public function SetTextFormat(ts: TextFormat)
	{
		mFormat = ts;
		
		Decorate();
	}
	
	
	public function SetStringFormat(fs: String)
	{
		mStringFormat = fs;
		
		SetValue(Std.parseInt(text));
	}
	

	public function SetIcon(icon: Bitmap, ?align: Int)
	{
		mIcon = icon;
		
		if (mIcon != null) {
			// left align
			mIcon.x = x;
			mIcon.y = y;
			
			x = mIcon.width + 2 + x;
	
			if (parent != null) {
				parent.addChild(mIcon);
			}			
		}
	}
	
	
	// private functions
	
	private function Decorate()
	{
		if (mFormat != null) {
			setTextFormat(mFormat);
		}
	}
	
	
	private function IntToStr(value: Int, ?nulls: Int): String
	{
		var str: String = Std.string(value);
		
		if (nulls != null) {
			var cnt: Int = nulls - str.length;
			for (i in 0...cnt) {
				str = "0" + str;
			}
		}
		
		return str;
	}
}